package com.orangelife.webservice.service.propFeeMeter.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.activation.DataHandler;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import jxl.CellView;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.propFeeComm.IPropFeeCommService;
import com.orangelife.service.propFeeComm.model.PropFeeCommDto;
import com.orangelife.service.propFeeCommInfo.IPropFeeCommInfoService;
import com.orangelife.service.propFeeMeter.IPropFeeMeterService;
import com.orangelife.service.propFeeMeter.model.EditMeterDto;
import com.orangelife.service.propFeeMeter.model.PropFeeMeterDto;
import com.orangelife.service.propFeeMeterRecord.IPropFeeMeterRecordService;
import com.orangelife.service.propFeeMeterRecord.impl.IImportRecord;
import com.orangelife.service.propFeeMeterRecord.model.PropFeeMeterRecordDto;
import com.orangelife.service.propFeeMeterRecordImportLog.IPropFeeMeterRecordImportLogService;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.HttpSvcUtils;
import com.orangelife.utils.JsonMapUtils;
import com.orangelife.utils.PropertyUtils;
import com.orangelife.utils.StringUtils;
import com.orangelife.utils.UrlPath;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.base.PageUtils;
import com.orangelife.webservice.service.propFeeMeter.IPropFeeMeterWebService;

/*****************************************************************
 * Copyright(C) ORANGELIFE Corporation 2015. All Rights Reserved.
 *****************************************************************/
/*
 * ============================================================== 功能名
 * propFeeMeter类 的WebService基本作业
 * 
 * @author zhr
 * 
 * @version 1.1.0
 * 
 * @date 2016-07-04 11:04:21
 * ==============================================================
 */
@Service("webservice_propFeeMeter")
public class PropFeeMeterWebServiceImpl extends BaseService implements
		IPropFeeMeterWebService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource(name = "propFeeMeterService")
	private IPropFeeMeterService propFeeMeterService;

	@Resource(name = "propFeeMeterRecordService")
	private IPropFeeMeterRecordService propFeeMeterRecordService;
	@Resource(name = "importRecord")
	private IImportRecord importRecord;
	@Resource(name = "propFeeCommService")
	private IPropFeeCommService propFeeCommService;
	@Resource(name = "propFeeCommInfoService")
	private IPropFeeCommInfoService propFeeCommInfoService;
	@Resource(name = "propFeeMeterRecordImportLogService")
	private IPropFeeMeterRecordImportLogService propFeeMeterRecordImportLogService;

	public IPropFeeMeterService getPropFeeMeterService() {
		return propFeeMeterService;
	}

	public void setPropFeeMeterService(IPropFeeMeterService propFeeMeterService) {
		this.propFeeMeterService = propFeeMeterService;
	}

	public IPropFeeMeterRecordService getPropFeeMeterRecordService() {
		return propFeeMeterRecordService;
	}

	public void setPropFeeMeterRecordService(
			IPropFeeMeterRecordService propFeeMeterRecordService) {
		this.propFeeMeterRecordService = propFeeMeterRecordService;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	@Override
	public Response addPropFeeMeter(HttpServletRequest servletRequest,
			PropFeeMeterDto propFeeMeter) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		int result = propFeeMeterService.addPropFeeMeter(propFeeMeter);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp();
	}

	@Override
	public Response editPropFeeMeter(HttpServletRequest servletRequest,
			PropFeeMeterDto propFeeMeter) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this
				.validateUUId(propFeeMeter.getMeterID(), "meterID");
		if (error != null) {
			return error;
		}

		/************************************************
		 * 输入参数检查
		 ************************************************/
		// TODO;

		int result = propFeeMeterService.editPropFeeMeter(propFeeMeter);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "修改实体成功");

		return this.normalResp();
	}

	@Override
	public Response deletePropFeeMeter(HttpServletRequest servletRequest,
			String meterID) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/

		int result = propFeeMeterService.deletePropFeeMeterByLogic(meterID);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功");

		return this.normalResp();
	}

	@Override
	public Response findPropFeeMeterByID(HttpServletRequest servletRequest,
			String meterID) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/

		PropFeeMeterDto propFeeMeter = propFeeMeterService
				.findPropFeeMeterByID(meterID);

		if (propFeeMeter != null) {
			List<String> ids = new ArrayList<String>();
			ids.add(propFeeMeter.getBelongID());
			Map<String, Object> result = new HashMap<String, Object>();
			Map<String, Object> map = new HashMap<String, Object>();

			/*
			 * if (propFeeMeter.getBelongType().equals("1")) { result =
			 * JsonMapUtils.getPageEntityMap(HttpSvcUtils.doPostSvc(
			 * UrlPath.bauthBuild, ids, pageUtils.getBaseSession()
			 * .getAccessToken())); if (result != null && result.size() > 0) {
			 * propFeeMeter .setBuildingID(result.get(0).get("buildingID") !=
			 * null ? result .get(0).get("buildingID").toString() : null);
			 * map.put("building", result.get(0));
			 * 
			 * } }
			 * 
			 * if (propFeeMeter.getBelongType().equals("2")) { result =
			 * JsonMapUtils.getPageEntityMap(HttpSvcUtils.doPostSvc(
			 * UrlPath.bauthUnit, ids, pageUtils.getBaseSession()
			 * .getAccessToken())); if (result != null && result.size() > 0) {
			 * propFeeMeter .setBuildingID(result.get(0).get("buildingID") !=
			 * null ? result .get(0).get("buildingID").toString() : null);
			 * map.put("unit", result.get(0)); } } if
			 * (propFeeMeter.getBelongType().equals("3")) { result =
			 * JsonMapUtils.getPageEntityMap(HttpSvcUtils.doPostSvc(
			 * UrlPath.bauthAparts, ids, pageUtils.getBaseSession()
			 * .getAccessToken())); if (result != null && result.size() > 0) {
			 * propFeeMeter .setBuildingID(result.get(0).get("buildingID") !=
			 * null ? result .get(0).get("buildingID").toString() : null);
			 * propFeeMeter .setUnitID(result.get(0).get("unitID") != null ?
			 * result .get(0).get("unitID").toString() : null);
			 * map.put("apartment", result.get(0)); } }
			 */

			if (propFeeMeter.getBelongType().equals("3")) {
				result = JsonMapUtils.getEntityMap(HttpSvcUtils.doPostSvc(
						UrlPath.getApartmentInfo, ids, pageUtils
								.getBaseSession().getAccessToken()));
				if (result != null && result.size() > 0) {
					JSONObject jsonObject = JSONObject.fromObject(result.get(
							propFeeMeter.getBelongID()).toString());
					map.put("comm", jsonObject.getString("comm"));
					map.put("buildingName",
							jsonObject.getString("buildingName"));
					map.put("unitName", jsonObject.getString("unitName"));
					map.put("apartmentName",
							jsonObject.getString("apartmentName"));
				}
				propFeeMeter.setComInfo(map);
			}

		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "查询实体成功");
		return this.normalResp(propFeeMeter);
	}

	@Override
	public Response getAllPropFeeMeter(HttpServletRequest servletRequest,
			String commID, String search, String tsCreate, String pageIndex,
			String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeeMeterService
				.findPropFeeMeterByPage(commID, tsCreate == null ? null
						: tsCreate, search == null ? null : search, pageUtils
						.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response bauthFindPropFeeMeter(HttpServletRequest servletRequest,
			List<String> propFeeMeter) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeMeter == null || propFeeMeter.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity",
					propFeeMeterService.bauthfindPropFeeMeter(propFeeMeter));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response bauthFindPropFeeMeters(HttpServletRequest servletRequest,
			Map<String, Object> propFeeMeter) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeMeter == null || propFeeMeter.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeeMeterService
							.bauthfindPropFeeMeterByMap(propFeeMeter)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response insertPropFeeMeter(HttpServletRequest servletRequest,
			PropFeeMeterDto propFeeMeter) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		int result = propFeeMeterService.bauthAddPropFeeMeter(propFeeMeter);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		return this.normalResp();
	}

	@Override
	public Response bauthEditPropFeeMeter(HttpServletRequest servletRequest,
			List<String> propFeeMeter) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeMeter == null || propFeeMeter.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity",
					propFeeMeterService.bauthDeletPropFeeMeter(propFeeMeter));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response getNoRecordPropFeeMeter(HttpServletRequest servletRequest,
			String commID, String buildingID, String search, String tsCreate,
			String pageIndex, String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);
		List<Map<String, Object>> list = propFeeMeterService
				.getNoRecordPropFeeMeter(map, tsCreate, search,
						pageUtils.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response bauthAddRecord(HttpServletRequest servletRequest,
			List<Map<String, Object>> propRecords) throws Exception {
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propRecords == null || propRecords.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			List<PropFeeMeterRecordDto> recordDtos = new ArrayList<PropFeeMeterRecordDto>();
			for (Map<String, Object> record : propRecords) {
				PropFeeMeterRecordDto propFeeMeterRecordDto = new PropFeeMeterRecordDto();

				if (!record.containsKey("meterID")) {
					throw new AppBizException(2, "亲，表信息");

				}

				if (!record.containsKey("period")) {
					throw new AppBizException(2, "亲，初始使用量");
				}

				if (record.get("meterID") == null) {
					throw new AppBizException(2, "亲，表信息");

				}

				if (record.get("period") == null) {
					throw new AppBizException(2, "亲，初始时间");
				}

				propFeeMeterRecordDto.setMeterID(record.get("meterID")
						.toString());
				propFeeMeterRecordDto
						.setPeriod(record.get("period").toString());
				propFeeMeterRecordDto.setRecord(StringUtils.toString(
						record.get("record"), null));
				propFeeMeterRecordDto.setUseAmount(StringUtils.toString(
						record.get("useAmount"), null));
				propFeeMeterRecordDto.setStatus("1");
				propFeeMeterRecordDto.setVer("0");
				List<Map<String, Object>> l = propFeeMeterRecordService
						.checkRecordIsExist(record);

				// 更新
				if (l != null && l.size() > 0) {
					propFeeMeterRecordDto.setRecordID(l.get(0).get("record_id")
							.toString());

					propFeeMeterRecordService
							.editPropFeeMeterRecord(propFeeMeterRecordDto);

				} else {

					propFeeMeterRecordService
							.addPropFeeMeterRecord(propFeeMeterRecordDto);
				}

				// recordDtos.add(propFeeMeterRecordDto);

			}

			// propFeeMeterRecordService.addPropFeeMeterRecord(recordDtos);
			map.put("errInfo", "ok");
			map.put("errCode", "0");
			logger.info(pageUtils.getBaseSession().getLoginName() + "在"
					+ pageUtils.getBaseSession().getLoginType() + "端"
					+ new Date() + "时" + "添加"
					+ JSONArray.fromObject(recordDtos) + "成功");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response downRecord(HttpServletRequest servletRequest,
			final HttpServletResponse servletResponse, String search,
			String commID, final String comm) throws Exception {

		if (StringUtils.isBlank(commID)) {
			throw new AppBizException(2, "亲小区信息");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);

		final List<Map<String, Object>> list = propFeeMeterService
				.getNoRecordPropFeeMeter(map, null, search);

		/************************************************
		 * 返回结果设定
		 ************************************************/
		String info = "表ID,表名,表类型,楼栋,单元,房号 ,类型 ,初始读数, 初始使用量,初始时间";
		final PropFeeCommDto propFeeComm = propFeeCommService
				.findPropFeeCommByID(commID);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		final String filename = df.format(new Date());
		StreamingOutput stream = null;
		final String propFeeMeterType[] = { "小区", "楼栋", "单元", "房屋" };

		final String infos[] = info.split(",");
		stream = new StreamingOutput() {
			public void write(OutputStream output) throws IOException,
					WebApplicationException {
				try {
					servletResponse.setContentType("application/vnd.ms-excel");
					servletResponse.setHeader(
							"Content-Disposition",
							"attachment; filename="
									+ new String((propFeeComm.getComm()
											+ "表读数初始化表" + filename + ".xls")
											.getBytes("UTF-8"), "iso8859-1"));
					servletResponse.setHeader("Pragma", "No-cache");
					servletResponse.setHeader("Cache-Control", "No-cache");
					servletResponse.setDateHeader("Expires", 0); // 这个地方一定要进行编码的转换要不然中文字符会出现乱码.
					// 设置下载头信息.end,
					// SimpleDateFormat df = new
					// SimpleDateFormat("yyyy-MM-dd");

					InputStream fis = null;
					// PrintWriter out = response.getWriter();
					try {
						output = servletResponse.getOutputStream();
						jxl.write.WritableWorkbook wwb = Workbook
								.createWorkbook(output);

						// NumberFormat nf = new NumberFormat("#00");

						jxl.write.WritableFont wfont = new jxl.write.WritableFont(
								WritableFont.createFont("宋体"), 12);

						WritableCellFormat font = new WritableCellFormat(
								NumberFormats.TEXT);
						font.setFont(wfont);
						font.setAlignment(jxl.format.Alignment.CENTRE);
						font.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
						// 水平居中对齐

						// 竖直方向居中对齐

						jxl.write.WritableSheet ws = wwb.createSheet("Sheet1",
								1); // 设置标题.ws.addCell(new
						for (int l = 0; l < infos.length; l++) {
							ws.addCell(new Label(l, 0, infos[l], font));

							if (l == 0) {
								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(10 * 265);// 设置列宽度（不设置的话是0，不会显示）
								ws.setColumnView(l, cv);
							} else {
								CellView cv = new CellView(); // 定义一个列显示样式
								cv.setFormat(font);// 把定义的单元格格式初始化进去
								cv.setSize(50 * 265);// 设置列宽度（不设置的话是0，不会显示）
								ws.setColumnView(l, cv);
							}
						}
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> map = PropertyUtils
									.turnToEntity1(list.get(j));
							int i = 0;

							ws.addCell(new Label(i, j + 1,
									map.get("meterID") != null ? map.get(
											"meterID").toString() : null, font));
							ws.addCell(new Label(i + 1, j + 1, map
									.get("meterName") != null ? map.get(
									"meterName").toString() : null, font));
							ws.addCell(new Label(i + 2, j + 1, map
									.get("meterTypeName") != null ? map.get(
									"meterTypeName").toString() : null, font));
							if (map.get("belongType").toString().equals("0")) {
							}
							if (map.get("belongType").toString().equals("1")) {
								ws.addCell(new Label(i + 3, j + 1, map
										.get("buildingName") != null ? map.get(
										"buildingName").toString() : null, font));
							}
							if (map.get("belongType").toString().equals("2")) {

								ws.addCell(new Label(i + 3, j + 1, map
										.get("buildingName") != null ? map.get(
										"buildingName").toString() : null, font));
								ws.addCell(new Label(i + 4, j + 1, map
										.get("unitName") != null ? map.get(
										"unitName").toString() : null, font));
							}
							if (map.get("belongType").toString().equals("3")) {
								ws.addCell(new Label(i + 3, j + 1, map
										.get("buildingName") != null ? map.get(
										"buildingName").toString() : null, font));
								ws.addCell(new Label(i + 4, j + 1, map
										.get("unitName") != null ? map.get(
										"unitName").toString() : null, font));
								ws.addCell(new Label(i + 5, j + 1, map
										.get("apartmentNum") != null ? map.get(
										"apartmentNum").toString() : null, font));
							}
							ws.addCell(new Label(
									i + 6,
									j + 1,
									map.get("belongType") != null ? propFeeMeterType[Integer
											.parseInt(map.get("belongType")
													.toString())] : null, font));

						}
						wwb.write();
						if (wwb != null) {
							wwb.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} finally {// 正常关闭输入输出流.
						if (fis != null) {
							fis.close();
						}
						if (output != null) {
							output.flush();
							output.close();
						}

					}

				} catch (Exception e) {
					e.printStackTrace();
					throw new WebApplicationException(e);

				}
			}
		};

		return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).build();
	}

	@Override
	public Response ImportRecord(HttpServletRequest servletRequest,
			HttpServletResponse servletResponse, String commID,
			List<Attachment> attachments) throws Exception {
		String fileName = "";
		if (attachments == null || attachments.size() == 0) {
			throw new AppBizException(100002, "请选择要上传的文件");
		}
		Sheet sheet = null;
		for (Attachment attachment : attachments) {

			DataHandler item = attachment.getDataHandler();
			fileName = item.getName();
			InputStream inputStream = item.getInputStream();
			fileName = new String(fileName.getBytes("iso-8859-1"), "utf-8");

			org.apache.poi.ss.usermodel.Workbook book = null;

			if (fileName.endsWith(".xls")) {
				book = new HSSFWorkbook(inputStream);
			} else if (fileName.endsWith(".xlsx")) {
				book = new XSSFWorkbook(inputStream);
			} else {
				throw new AppBizException(100002, "文件格式错误");
			}
			sheet = book.getSheetAt(0);// 第一个工作表
			importRecord.importRecord(sheet, commID, fileName);
		}

		return this.normalResp();

	}

	@Override
	public Response bauthFindPropFeeMeterTree(
			HttpServletRequest servletRequest, Map<String, Object> propFeeMeter)
			throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeeMeter == null || propFeeMeter.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeeMeterService
							.bauthfindPropFeeMeterTreeByMap(propFeeMeter)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response findBudingUnitApartTree(HttpServletRequest servletRequest,
			String commID, String meterTypeID) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {
			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeeMeterService.findbuildUnitApartTree(
							commID, meterTypeID)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();
	}

	@Override
	public Response getInitRecordPropFeeMeter(
			HttpServletRequest servletRequest, String commID,
			String buildingID, String search, String tsCreate,
			String pageIndex, String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("commID", commID);
		List<Map<String, Object>> list = propFeeMeterService
				.getInitRecordPropFeeMeter(map, tsCreate, search,
						pageUtils.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response getImportLogInfos(HttpServletRequest servletRequest,
			String commID, String search, String tsCreate, String pageIndex,
			String pageSize) throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/

		List<Map<String, Object>> list = propFeeMeterRecordImportLogService
				.findPropFeeMeterRecordImportLogByPage(commID, tsCreate,
						search, pageUtils.getiPageIndex(),
						pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response getMeterRecord(HttpServletRequest servletRequest,
			String commID, String meterTypeID, String period, String type,
			String buildingID, String unitID, String isempty, String pageIndex,
			String pageSize) throws Exception {
		
//		propFeeMeterRecordService.findPropFeeMeterRecordByRelevantID(null, meterID, status, record, period, useAmount, ver)
		
		// TODO Auto-generated method stub
		Map<String,Object> param=new HashMap<>();
		param.put("commID", commID);
		param.put("period", period);
		
		
		if("0".equals(type)){
			List <Map<String,Object>>l=	propFeeMeterService.selectCommMeterRecord(param);

			return this.normalResp(1, 1, 0l, PropertyUtils.turnToEntity(l));
			
		}
		
		return this.normalResp();
	}

	@Override
	public Response getMeterRecordBymap(HttpServletRequest servletRequest,
			Map<String, Object> params) throws Exception {
		
		 String pageIndex=StringUtils.toString(params.get("pageIndex"), "1");
		 String pageSize=StringUtils.toString(params.get("pageSize"), "10");

		              if(params.get("pageIndex")==null){
			
			
		            	  params.put("pageIndex","1");
		                  }
		              if(params.get("pageSize")==null){
		            		
		            		
		            	  params.put("pageSize","10");
		                  }
				PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
						pageIndex, pageSize);
				if (pageUtils.getResponse() != null) {
					return pageUtils.getResponse();
				}

				
				/************************************************
				 * 查询列表
				 ************************************************/
				List<Map<String, Object>> list  =propFeeMeterService.selectMeterRecord(params);

				/************************************************
				 * 返回结果设定
				 ************************************************/
				Long total = ((Page<Map<String, Object>>) list).getTotal();

				logger.info(pageUtils.getBaseSession().getLoginName() + "在"
						+ pageUtils.getBaseSession().getLoginName() + new Date()
						+ "查询实体成功");

				return this.normalResp(pageUtils.getiPageIndex(),
						pageUtils.getiPageSize(), total,
						PropertyUtils.turnToEntity(list));
		
	
	}

	@Override
	public Response editMeterRecord(HttpServletRequest servletRequest,
			EditMeterDto editMeterDto) throws Exception {
		PageUtils pageUtils = this.validateLogin(servletRequest);
		if (pageUtils.getResponse()!= null) {
			return pageUtils.getResponse();
		}
		editMeterDto.setUserID(pageUtils.getBaseSession().getUserID());
		editMeterDto.setTrueName(pageUtils.getBaseSession().getTrueName());
		
         String curDate=		propFeeCommInfoService.findValByCode(editMeterDto.getCommID(), "curDate");
		if(curDate==null){
			
			return this.abnormalResp(-1, "缴费未配置");
		}
		editMeterDto.setInitDate(curDate);
		
		if(editMeterDto.getEditType()==null||!"2".equals(editMeterDto.getEditType())){
			propFeeMeterService.editMeterRecords(editMeterDto);
			
		}
		else{
			propFeeMeterService.editMeterRecordAndMoney(editMeterDto);
			
		}
		
		
		// TODO Auto-generated method stub
		return this.normalResp();
	}
}
